package com.ericsson.common.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ericsson.common.exception.DBConnectionException;
import com.ericsson.common.xml.XMLException;
import com.ericsson.common.xml.XMLParser;


public class DatabaseMng
{
	protected  DataSource ds = null;
	protected  InitialContext ctx =null;
	protected static DatabaseMng dbconnector=null;
	protected static Object lock=new Object();
	protected static String filename="/DataSource.xml";
	private static Log log=LogFactory.getLog(DatabaseMng.class);
	
	
	private DatabaseMng()
	{
		String dataSource;
		try
		{
			XMLParser parser=new XMLParser(DatabaseMng.class.getResource(filename).getPath());
			dataSource=parser.getElement("Runtime[0].DataSource[0]");
			try
			{
				ctx = new InitialContext();
				ds = (DataSource)ctx.lookup(dataSource);
			}
			catch (NamingException e)
			{
				log.fatal("\r FATAL error during reading datasource from the JNDI,The System terminated!",e);
				System.exit(-1);
			}
			
		}
		catch (XMLException e)
		{
			log.fatal("\r FATAL error during reading the system parameters,The system terminated",e);
			System.exit(-1);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
	}
	
	public static DatabaseMng getInstance()
	{
		if (dbconnector==null)
		{
			synchronized(lock)
			{
				dbconnector=new DatabaseMng();
			}
			
		}
		return dbconnector;
	}
	
	public  Connection getConnection() throws DBConnectionException
	{
		try
		{
			return ds.getConnection();
		}
		catch (SQLException e)
		{
			log.error("\r get the database connection failure,try again!",e);
			throw new DBConnectionException("������æ�����Ժ�����!",e);
		}
	}
	public  DataSource getDataSource() 
	{
		return ds;		
	}
	
}
